package com.wing.wcabinet.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.CabinetCargoSpace;
import com.wing.cabinet.model.entity.CellInventoryInout;
import com.wing.cabinet.model.entity.StorageInventoryInout;
import com.wing.cabinet.model.entity.UseInventoryInout;
import com.wing.cabinet.model.request.CellInventoryInoutForm;
import com.wing.cabinet.model.request.StorageInventoryInoutForm;
import com.wing.cabinet.model.request.UseInventoryInoutDetailForm;
import com.wing.cabinet.model.response.CabinetCargoSpaceVO;
import com.wing.common.exception.BusinessException;
import com.wing.wcabinet.model.entity.WcabCellInventoryInout;
import com.wing.wcabinet.model.entity.WcabUseInventoryInout;
import com.wing.wcabinet.model.request.WcabCellInventoryInoutForm;
import com.wing.wcabinet.model.response.WcabCellInventoryInoutDetailVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.wcabinet.model.entity.WcabCellInventoryInoutDetail;
import com.wing.wcabinet.model.request.WcabCellInventoryInoutDetailForm;
import com.wing.wcabinet.service.WcabCellInventoryInoutDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-售刀柜上货(上货主表无展示)/领取明细管理", tags = "#/wcabinet/wcabCellInventoryInoutDetail")
@RestController("wcabCellInventoryInoutDetailController")
@RequestMapping("wcabinet/admin/wcabCellInventoryInoutDetail")
@RequiredArgsConstructor
@Slf4j
public class WcabCellInventoryInoutDetailController {

    private final WcabCellInventoryInoutDetailService wcabCellInventoryInoutDetailService;




    @ApiOperation(value = "查询所有售刀柜上货(上货主表无展示)/领取明细", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<WcabCellInventoryInoutDetailVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long inoutId
            ,Long id

    ){

        Page<WcabCellInventoryInoutDetail> pg = new Page<>(page, limit);
        Map queryParam=new HashMap();
        queryParam.put("sort",StrUtil.toUnderlineCase(sort));
        queryParam.put("order",order);
        queryParam.put("inoutId",inoutId);
        queryParam.put("id",id);

        IPage<WcabCellInventoryInoutDetailVO> list = wcabCellInventoryInoutDetailService.pageList(pg,queryParam);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加售刀柜上货(上货主表无展示)/领取明细", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(WcabCellInventoryInoutDetailForm.Add.class) WcabCellInventoryInoutDetailForm wcabCellInventoryInoutDetailForm) {
        if (wcabCellInventoryInoutDetailService.add(wcabCellInventoryInoutDetailForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改售刀柜上货(上货主表无展示)/领取明细", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(WcabCellInventoryInoutDetailForm.Update.class) WcabCellInventoryInoutDetailForm wcabCellInventoryInoutDetailForm) {
        WcabCellInventoryInoutDetail wcabCellInventoryInoutDetail = wcabCellInventoryInoutDetailService.getById(wcabCellInventoryInoutDetailForm.getId());
        if(wcabCellInventoryInoutDetail == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(WcabCellInventoryInoutDetail.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(wcabCellInventoryInoutDetailForm, wcabCellInventoryInoutDetail, copyOptions);
        if (wcabCellInventoryInoutDetailService.updateById(wcabCellInventoryInoutDetail)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除售刀柜上货(上货主表无展示)/领取明细", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wcabCellInventoryInoutDetailId", value = "售刀柜上货(上货主表无展示)/领取明细id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long wcabCellInventoryInoutDetailId) {
        if (wcabCellInventoryInoutDetailService.removeById(wcabCellInventoryInoutDetailId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "售刀柜领取", notes = "领取")
    @PostMapping("/inventoryOut")
    public JsonResult inventoryOut(@RequestBody WcabCellInventoryInoutForm cellInventoryInoutForm){
        try{
            checkParams(cellInventoryInoutForm.getDetailList());
            WcabCellInventoryInout wcabCellInventoryInout=wcabCellInventoryInoutDetailService.inventoryOut(cellInventoryInoutForm.getDetailList(),cellInventoryInoutForm.getDeviceCode(),WcabCellInventoryInout.BusinessType.normal,WcabCellInventoryInout.OperationType.out,null);
            return JsonResult.success("领取成功",wcabCellInventoryInout);
        }catch (Exception e){
            log.error("cell inventory out fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    void checkParams(List<WcabCellInventoryInoutDetailForm> detailList){
        if (CollectionUtil.isEmpty(detailList)){
            throw new BusinessException("缺少明细参数");
        }
        for (WcabCellInventoryInoutDetailForm wcabCellInventoryInoutDetailForm:detailList){
            if (wcabCellInventoryInoutDetailForm.getWeight()==null||wcabCellInventoryInoutDetailForm.getWeight().doubleValue()<=0||
                    wcabCellInventoryInoutDetailForm.getQuantity()==null||wcabCellInventoryInoutDetailForm.getQuantity()<=0){
                throw new BusinessException("重量/数量参数异常");
            }
        }
    }

    @ApiOperation(value = "存维修", notes = "存维修")
    @PostMapping("/repair/inventoryIn")
    public JsonResult repairInventoryIn(@RequestBody WcabCellInventoryInoutForm cellInventoryInoutForm){
        try{
            checkParams(cellInventoryInoutForm.getDetailList());
            cellInventoryInoutForm.setBusinessType(WcabCellInventoryInout.BusinessType.repair);
            cellInventoryInoutForm.setOperationType(WcabCellInventoryInout.OperationType.repairIn);
            wcabCellInventoryInoutDetailService.inventoryIn(cellInventoryInoutForm);
            return JsonResult.success();
        }catch (Exception e){
            log.error("repair inventory in fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "存报废", notes = "存维修")
    @PostMapping("/recycle/inventoryIn")
    public JsonResult recycleInventoryIn(@RequestBody WcabCellInventoryInoutForm cellInventoryInoutForm){
        try{
            checkParams(cellInventoryInoutForm.getDetailList());
            cellInventoryInoutForm.setBusinessType(WcabCellInventoryInout.BusinessType.recycle);
            cellInventoryInoutForm.setOperationType(WcabCellInventoryInout.OperationType.recycleIn);
            wcabCellInventoryInoutDetailService.inventoryIn(cellInventoryInoutForm);
            return JsonResult.success();
        }catch (Exception e){
            log.error("recycle inventory in fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "退货", notes = "退货")
    @PostMapping("/return/inventoryIn")
    public JsonResult returnInventoryIn(@RequestBody WcabCellInventoryInoutForm cellInventoryInoutForm){
        try{
            checkParams(cellInventoryInoutForm.getDetailList());
            cellInventoryInoutForm.setBusinessType(WcabCellInventoryInout.BusinessType.normal);
            cellInventoryInoutForm.setOperationType(WcabCellInventoryInout.OperationType.returnIn);
            wcabCellInventoryInoutDetailService.inventoryIn(cellInventoryInoutForm);
            return JsonResult.success();
        }catch (Exception e){
            log.error("recycle inventory in fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "盘验（柜子面板）", notes = "盘验")
    @PostMapping("/check4web")
    public JsonResult check4Cab(@RequestBody WcabCellInventoryInoutForm storageInventoryInoutForm){
        try{
            log.info("check params:{}", JSON.toJSONString(storageInventoryInoutForm));
            wcabCellInventoryInoutDetailService.check4Wx(storageInventoryInoutForm);
            return JsonResult.success();
        }catch (Exception e){
            log.error("check fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }




}
